import { md5 } from "js-md5";
let sm2 = require('sm-crypto').sm2

export async function getSign(method,url,body) {
	let token = uni.getStorageSync('token');
	if (!token) {
		token = ''
	}
	let urlParams = token;
	let bodyStringify = body

	if (typeof body != 'string') {
		bodyStringify = JSON.stringify(body)
	}
	let allParamStr = urlParams
	if (method != 'get') {
		allParamStr = urlParams+bodyStringify
	}
	let md5Str = md5(allParamStr)
	let base64Sign = ''
	let privateKey = uni.getStorageSync('privateKey')
	if (privateKey) {
		let hexSign = sm2.doSignature(md5Str,privateKey, {
			hash: true,
			der: true
		})

		base64Sign = hexToBase64(hexSign)
	}
	return base64Sign;
}

export function hexToBase64(str) {
  var digits =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var base64_rep = "";
  var ascv;
  var bit_arr = 0;
  var bit_num = 0;
  for (var n = 0; n < str.length; ++n) {
    if (str[n] >= "A" && str[n] <= "Z") {
      ascv = str.charCodeAt(n) - 55;
    } else if (str[n] >= "a" && str[n] <= "z") {
      ascv = str.charCodeAt(n) - 87;
    } else {
      ascv = str.charCodeAt(n) - 48;
    }
    bit_arr = (bit_arr << 4) | ascv;
    bit_num += 4;
    if (bit_num >= 6) {
      bit_num -= 6;
      base64_rep += digits[bit_arr >>> bit_num];
      bit_arr &= ~(-1 << bit_num);
    }
  }

  if (bit_num > 0) {
    bit_arr <<= 6 - bit_num;
    base64_rep += digits[bit_arr];
  }
  var padding = base64_rep.length % 4;
  if (padding > 0) {
    for (var n = 0; n < 4 - padding; n++) {
      base64_rep += "=";
    }
  }
  return base64_rep;
}
